package com.ellecity06.cwhiskymall.ui.login

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.core.widget.addTextChangedListener
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.load
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.onDebounceClick
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.utils.logD
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.databinding.ActivityLoginBinding
import com.ellecity06.cwhiskymall.timer.tickFlow
import com.ellecity06.cwhiskymall.ui.MainActivity
import com.ellecity06.cwhiskymall.ui.MainIntent
import com.ellecity06.cwhiskymall.ui.MainState
import com.ellecity06.cwhiskymall.ui.login.forget.ForgetPwdActivity
import com.ellecity06.cwhiskymall.ui.register.RegisterActivity
import com.ellecity06.cwhiskymall.ui.register.RegisterIntent
import com.ellecity06.cwhiskymall.ui.register.RegisterState
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.ellecity06.cwhiskymall.view.dialog.VersionUpdateDialog
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2023/4/13 16:09
 * @des
 */
class LoginActivity : BaseMvvmActivity<ActivityLoginBinding, LoginViewModel>(),
    View.OnClickListener {
    // (属性) 用于取消，确保不会重复收集流
    private var mTickJob: Job? = null
    private var isPwd = true
    override val userBaseTitle: Boolean
        get() = false

    companion object {
        fun launch(context: Context) {
            context.startActivity(Intent(context, LoginActivity::class.java))
        }
    }

    override fun inflateBinding(): ActivityLoginBinding =
        ActivityLoginBinding.inflate(layoutInflater)

    override fun initialize(savedInstanceState: Bundle?) {
        selectLoginPassword()
        checkHasNewVersion()
    }

    override fun initObserver() {

        viewModel.state.observeEvent(this) {
            when (it) {
                is LoginState.Checked -> {
                    setCheckRes(it.checked)
                }

                is LoginState.SmdCodeSuccess -> {
                    ToastUtils.show("验证码已发送")
                    countDown()
                }

                is LoginState.LoginSuccess -> {
                    ToastUtils.show("登录成功")
                    MainActivity.launch(this)
                    finish()

                }

                is LoginState.GetPicCodeSuccess -> {
                    binding.ivPicCode.load(this, it.url)
                }

                is LoginState.ShowDialog -> {
                    VersionUpdateDialog(this, it.data).show()
                }

                else -> {}
            }
        }
    }


    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            titleBar(binding.toolBar)
        }
    }

    override val darkFont: Boolean
        get() = false

    override fun initEvent() {
        binding.ivEye.setOnClickListener(this)
        binding.tvUserAgreement.setOnClickListener(this)
        binding.tvPrivateAgreement.setOnClickListener(this)
        binding.tvPasswordLogin.setOnClickListener(this)
        binding.tvSmsLogin.setOnClickListener(this)
        binding.tvLogin.setOnClickListener(this)
        binding.tvRegister.setOnClickListener(this)
        binding.ivCheck.setOnClickListener(this)
        binding.tvSendTitle.setOnClickListener(this)
        binding.btnForgetPwd.setOnClickListener(this)
        binding.ivPicCode.setOnClickListener(this)
        binding.etPhone.addTextChangedListener(textWatch)
    }


    private fun setCheckRes(checked: Boolean) {
        binding.ivCheck.setImageResource(if (checked) R.mipmap.icon_check_select else R.mipmap.icon_check_unselect)
    }


    override fun initData() {
    }


    private fun showPasswordLayout() {
        binding.viewPassword.visibility = View.VISIBLE
        binding.viewSms.visibility = View.GONE
        selectLoginPassword()
    }

    private fun showSmsLayout() {
        binding.viewPassword.visibility = View.GONE
        binding.viewSms.visibility = View.VISIBLE
        selectLoginPassword()
    }

    private val textWatch = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if (isPwd) {
                return
            }
            if (!s.isNullOrEmpty() && s.toString().length == 11) {
                binding.layoutPicCode.visibility = View.VISIBLE
                lifecycleScope.launch {
                    viewModel.intentChannel.send(LoginIntent.GetPicCode(s.toString()))
                }
            } else {
                binding.layoutPicCode.visibility = View.GONE
            }
        }

    }

    private fun selectLoginPassword() {
        binding.ivPwdSelect.visibility = if (isPwd) View.VISIBLE else View.GONE
        binding.ivSmsSelect.visibility = if (isPwd) View.GONE else View.VISIBLE
        val phone = binding.etPhone.text.toString().trim()
        if (!isPwd && phone.isNotEmpty() && phone.length == 11) {
            binding.layoutPicCode.visibility = View.VISIBLE
            val phoneNum = binding.etPhone.text.toString().trim()
            lifecycleScope.launch {
                viewModel.intentChannel.send(LoginIntent.GetPicCode(phoneNum))
            }
        } else {
            binding.layoutPicCode.visibility = View.GONE
        }
    }

    /**
     * 密码是否可见
     * 1 明文
     */
    private fun setEysSee(editText: EditText, imageView: ImageView) {
        if (editText.inputType == 1) {
            editText.inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
        } else {
            editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_NORMAL
        }
        setSye(imageView, editText.inputType == 1)
        //光标位置
        editText.setSelection(editText.text.toString().length)
    }

    private fun setSye(imageView: ImageView, isSee: Boolean) {
        imageView.setImageResource(if (isSee) R.mipmap.icon_eye_open else R.mipmap.icon_eye_close)
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_check -> {
                lifecycleScope.launch {
                    viewModel.intentChannel.send(LoginIntent.ChangeCheck)
                }
            }

            R.id.tv_password_login -> {
                isPwd = true
                viewModel.changeLogin(0)
                showPasswordLayout()

            }

            R.id.tv_sms_login -> {
                isPwd = false
                viewModel.changeLogin(1)
                showSmsLayout()
            }

            R.id.tv_send_title -> {
                val phone = binding.etPhone.text.toString().trim()
                val imagCode = binding.etPicCode.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(LoginIntent.SendSmsCode(imagCode, phone))
                }

            }

            R.id.tv_login -> {
                val phone = binding.etPhone.text.toString().trim()
                val password = binding.etPassword.text.toString().trim()
                val code = binding.etSmsCode.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(
                        LoginIntent.Login(
                            phone = phone,
                            password = password,
                            code = code
                        )
                    )
                }
            }

            R.id.tv_register -> {
                RegisterActivity.launch(this)
            }

            R.id.iv_eye -> {
                setEysSee(binding.etPassword, binding.ivEye)
            }

            R.id.btn_forget_pwd -> {
                ForgetPwdActivity.launch(this, 0)
            }

            R.id.iv_pic_code -> {
                val phone = binding.etPhone.text.toString().trim()
                lifecycleScope.launch {
                    viewModel.intentChannel.send(LoginIntent.GetPicCode(phone))
                }
            }
            binding.tvUserAgreement.id -> {
                WebHelper.toUserAgreement(this)
            }

            binding.tvPrivateAgreement.id -> {
                WebHelper.toPrivateAgreement(this)
            }
        }
    }

    // (函数)，开始倒计时
    private fun countDown() {
        var duration = 60
        mTickJob?.cancel()
        mTickJob = tickFlow {
            duration -= 1
            if (duration <= 0) {
                mTickJob?.cancel()
                // 结束
                binding.tvSendTitle.text = "发送验证码"
                binding.tvSendTitle.isEnabled = true
            } else {
                binding.tvSendTitle.text = "${duration}后重发"
                binding.tvSendTitle.isEnabled = false
            }
        }
    }

    /**
     * 检查版本更新
     */
    private fun checkHasNewVersion() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(LoginIntent.FetchLastVersion)
        }
    }

    override fun onDestroy() {
        binding.etPhone.removeTextChangedListener(textWatch)
        super.onDestroy()
    }
}